package me.zhengjie.modules.device.service.impl;

import me.zhengjie.modules.device.domain.GasDevice;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.modules.device.repository.GasDeviceRepository;
import me.zhengjie.modules.device.service.GasDeviceService;
import me.zhengjie.modules.device.service.dto.GasDeviceDTO;
import me.zhengjie.modules.device.service.mapper.GasDeviceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;

/**
* @author 张鹏
* @date 2019-05-08
*/
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class GasDeviceServiceImpl implements GasDeviceService {

    @Autowired
    private GasDeviceRepository gasDeviceRepository;

    @Autowired
    private GasDeviceMapper gasDeviceMapper;

    @Override
    public GasDeviceDTO findById(Long id) {
        Optional<GasDevice> gasDevice = gasDeviceRepository.findById(id);
        ValidationUtil.isNull(gasDevice,"GasDevice","id",id);
        return gasDeviceMapper.toDto(gasDevice.get());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public GasDeviceDTO create(GasDevice resources) {
        return gasDeviceMapper.toDto(gasDeviceRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(GasDevice resources) {
        Optional<GasDevice> optionalGasDevice = gasDeviceRepository.findById(resources.getId());
        ValidationUtil.isNull( optionalGasDevice,"GasDevice","id",resources.getId());

        GasDevice gasDevice = optionalGasDevice.get();
        // 此处需自己修改
        resources.setId(gasDevice.getId());
        gasDeviceRepository.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        gasDeviceRepository.deleteById(id);
    }
}